﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Newtonsoft.Json;

namespace BlockMain_Class
{
    public static class AddBlock
    {

        private static Object thisLock = new Object();
        public static string Add(Record r, string nowpeer)
        {
            lock (thisLock)
            {
                PeerDB.dbName = "Peer_" + nowpeer; //当前节点
                PeerMongodbHelpers<AccountBook> mon = new PeerMongodbHelpers<AccountBook>();
                try
                {
                    //Checkt();
                    //生成预选链
                    //获取最后一条数据
                    var last = mon.QueryAll().ToList().LastOrDefault();
                    if (last != null)
                    {

                        Block oldBlock = new Block
                        {
                            Index = last.Height,
                            TimeStamp = last.TimeStamp,
                            Data = last.Data,
                            Hash = last.Hash,
                            PrevHash = last.PrevHash,
                        };

                        //生成新的 
                        Block newBlock = BlockGenerator.GenerateBlock(oldBlock, r.JsonData, r.AddTime);

                        //验证区块的有效性
                        if (BlockGenerator.IsBlockValid(newBlock, oldBlock))
                        {
                            //追加缓存

                            //追加当前区块到链中
                            AccountBook b = new AccountBook();
                            b.Height = newBlock.Index;
                            b.TimeStamp = newBlock.TimeStamp;
                            b.Data = r.JsonData;
                            b.Hash = newBlock.Hash;
                            b.PrevHash = newBlock.PrevHash;
                            var result = mon.Insert(b);
                        }

                    }
                    else
                    {
                        AccountBook b = new AccountBook();
                        //没有最后一条追加创世链
                        b.Height = 0;
                        b.TimeStamp = "1525716699872";
                        b.Data = "欢迎你光临我的联盟链..";
                        b.Hash = "";
                        b.PrevHash = "";
                        var result = mon.Insert(b);
                        Add(r, nowpeer);
                    }


                }
                catch (Exception ex)
                {

                }
            }
            return "ok";
        }


        /// <summary>
        /// 一致性处理
        /// </summary>
        /// <param name="mon"></param>
        /// <returns></returns>
        public static bool Checkt()
        {
            return true;
        }

    }
}
